// JavaScript Document
document.write('<script src="../static/js/check_input.js" type="text/javascript"></script>');
var passEmail = ''; /*用于存放通过验证的邮箱地址*/
var passUsername = ''; /*用于存放通过验证的用户名*/
var passPhone = ''; /*用于存放通过验证的手机号码*/
$(function(){
	/*初始化验证码*/-
    getCaptcha();

	/*密码明文和秘文显示*/
	$('.password-eye').on('click', function(){
		if($('.text-input.pwd').attr('type') == 'password'){
			$('.text-input.pwd').attr('type', 'text');
			$('.password-eye').attr('class','glyphicon glyphicon-eye-open password-eye');
		}else{
			$('.text-input.pwd').attr('type', 'password');
			$('.password-eye').attr('class','glyphicon glyphicon-eye-close password-eye');
		}
	});
	
	/*邮箱注册与手机号注册切换*/
	$('#form-email').addClass('active');
	$('.form-nav div li').on('click',function(){
		$(this).addClass('bbottom').siblings('li').removeClass('bbottom');
		var idex = $(this).index();
		$('.form-panel form').eq(idex).addClass('active').siblings('form').removeClass('active');
	});
	
	/*监听复选框开启下一步按钮*/
	$('#form-email .checkh').on('change', function(){
		if($(this).is(':checked') === true){
			$('#email-next').attr('disabled', false);
		}else if($(this).is(':checked') === false){
			$('#email-next').attr('disabled', true);
		}
	})
	$('#form-phone .checkh').on('change', function(){
		if($(this).is(':checked') === true){
			$('#phone-next').attr('disabled', false);
		}else if($(this).is(':checked') === false){
			$('#phone-next').attr('disabled', true);
		}
	})

	/*邮箱注册点击下一步*/
	$('#email-next').on('click',function(){
		var email = $('#email').val();
		var code = $('#code').val();
		var password = $('#form-email .text-input.pwd').val();
		var reEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
		var pass = true;
		if(email === null || email.trim(' ') === ''){
            $('#email').parent().children('.error').removeClass('.success').html('<i class="fa fa-times-circle"></i>请输入邮箱地址');
            pass = false;
		}else if(!reEmail.test(email)){
            $('#email').parent().children('.error').removeClass('.success').html('<i class="fa fa-times-circle"></i>请输入正确的邮箱地址');
            pass = false;
		}
		if(code === null || code.trim(' ') === ''){
            $('#code').parent().children('.error').html('<i class="fa fa-times-circle"></i>请输入验证码');
            pass = false;
		}
		if(password === null ||password.trim(' ') === ''){
            $('#form-email .text-input.pwd').parent().children('.error').html('<i class="fa fa-times-circle"></i>请设置登录密码');
            pass = false;
		}
		if(email != passEmail){
            pass = false;
        }
        if(pass) {
            var eToken = $.cookie('ETOKEN');
            var field = $('#code');
            $.ajax({
                url: 'code',
                method: 'get',
                data:{
                    code : field.val(),
                    eToken : eToken
                },
                dataType: 'json',
                success: function(data) {
                    if(data.code === 1001){
                        $('.form-box').hide();
                        $('#emailOne').hide();
                        var emailTwoHTML = '<div class="form-group" style="margin-top:100px;">';
                        emailTwoHTML += '<label for="username" class="text-label">用户名</label>';
                        emailTwoHTML += '<input type="text" class="form-control-static text-input" name="username" id="username" maxlength="16" placeholder="设置用户名" />';
                        emailTwoHTML += '<span class="error"></span>';
                        emailTwoHTML += '</div>';
                        emailTwoHTML += '<div class="form-group">';
                        emailTwoHTML += '<label for="nickname" class="text-label">昵称</label>';
                        emailTwoHTML += '<input type="text" class="form-control-static text-input" name="nickname" id="nickname" placeholder="设置昵称" />';
                        emailTwoHTML += '<span class="error"></span>';
                        emailTwoHTML += '</div>';
                        emailTwoHTML += '<div class="radio radio-sex">';
                        emailTwoHTML += '<span class="text-label">性别</span>';
                        emailTwoHTML += '<label><input type="radio" name="gender" checked="true" value="0" /><i class="radio-bui"></i>男</label>';
                        emailTwoHTML += '<label><input type="radio" name="gender" value="1" /><i class="radio-bui"></i>女</label>';
                        emailTwoHTML += '</div>';
                        emailTwoHTML += '<div class="form-group">';
                        emailTwoHTML += '<label for="birthday" class="text-label">出生日期</label>';
                        emailTwoHTML += '<input type="text" class="form-control-static text-input" name="birthday" id="birthday" placeholder="设置出生日期(yyyy-mm-dd)" />';
                        emailTwoHTML += '<span class="error"></span>';
                        emailTwoHTML += '</div>';
                        emailTwoHTML += '<div class="form-group">';
                        emailTwoHTML += '<label for="job" class="text-label">职务</label>';
                        emailTwoHTML += '<input type="text" class="form-control-static text-input" name="job" id="job" placeholder="设置职务" />';
                        emailTwoHTML += '<span class="error"></span>';
                        emailTwoHTML += '</div>';
                        emailTwoHTML += '<div class="form-group">';
                        emailTwoHTML += '<input type="button" class="btn btn-primary btn-register" value="注册" id="register" />';
                        emailTwoHTML += '</div>';
                        $('#emailTwo').html(emailTwoHTML);
                        $('#birthday').flatpickr();

                        /*为所有input标签添加focus事件*/
                        $('input').on('focus', function () {
                            removeHint(this);
                        })
                        /*为用户名添加校验查询*/
                        checkUsernameIsUsable();
                        /*注册表单校验提交*/
                        $('#register').on('click', function () {
                            var form = $('#form-email');
                            var username = $('#username').val();
                            var pass = validateForm(form);
                            if (pass && passUsername === username) {
                                $.ajax({
                                    url: 'create/em',
                                    method: 'POST',
                                    data: form.serialize(),
                                    dataType: 'json',
                                    success: function (data) {
                                        $('#register').attr('disabled', 'true');
                                        if(data.code === 1001){
                                            layer.msg(data.message + '，请前往邮箱激活账号', {time:3000});
                                            setTimeout(function() {
                                                location.href = 'http://192.168.43.114:8080/loginnew/index';
                                            }, 3000);
                                        }else if(data.code === 1002){
                                            var errors = data.data.errors;
                                            var text = '';
                                            for(var i=0;i<errors.length;i++)
                                                text += errors[i] + '\n'
                                            alert(text);
                                            setTimeout(function() {
                                                location.href = 'http://192.168.43.114:8080/registernew/index';
                                            }, 2000);
                                        }
                                    },
                                    error: function (err) {
                                        alert('回调接口函数失败');
                                    }

                                })
                            }
                        })
                    }else {
                        field.parent().children('.error').html('<i class="fa fa-times-circle"></i>' + data.message + '，请重新输入!!!');
                        getCaptcha();
                    }
                },
                error: function (err) {
                    alert('回调函数接口失败');
                }
            })
        }
	})

	/*监听手机号码输入框开启获取短信验证码*/
	$('#phone').on('input propertychange change', function(){
		var size = $('#phone').val().length;
		if(size === 11){
			$('#phoneCode').removeAttr('disabled');
			$('#getPhoneCode').removeAttr('disabled');
			$('#getPhoneCode').css('background-color', '#428bca');
		}else{
            $('#phoneCode').attr('disabled', 'true');
            $('#getPhoneCode').attr('disabled', 'true');
            $('#getPhoneCode').css('background', '#ccc');
		}
	})
	
	/*点击发送短信验证码*/
	$('#getPhoneCode').on('click', function(){
	    var el = this;
	    var phone = $('#phone');
        var passCheck = true;
        $(el).attr('disabled', true);
        if(passPhone !== phone.val())  passCheck = false;
        if(passCheck){
            $.ajax({
                url: 'smsCode',
                method: 'POST',
                data: {
                    phone : phone.val()
                },
                dataType: 'json',
                success: function(data) {
                    console.log(JSON.stringify(data))
                    if(data.code === 1001){
                        layer.msg(data.message, {time: 1000});
                        var time = data.data.time;
                        $(el).css('background-color', '#ccc');
                        var interval = setInterval(function() {
                            $(el).html(time-- + "&nbsp;秒");
                            if(time == 0){
                                $(el).html("获取验证码");
                                $(el).removeAttr('disabled');
                                $(el).css('background-color', '#428bca');
                                clearInterval(interval);
                            }
                        }, 1000);
                    }else if(data.code === 1002){
                        layer.msg(data.message, {time: 3000});
                        $(el).attr('disabled', false);
                    }
                },
                error: function(err) {
                    console.log(JSON.stringify(err))
                }
            })
        }else
            return;
	})
	
	/*手机号注册*/
	$('#phone-next').on('click',function(){
        var pass = true;
		var phone = $('#phone').val();
		var phoneCode = $('#phoneCode').val();
		var password = $('#form-phone .text-input.pwd').val();
		var rePhone = /^1[3456789]\d{9}$/;
		if(phone === null || phone.trim() === ''){
            $('#phone').parent().children('.error').html('<i class="fa fa-times-circle"></i>请输入手机号码');
            pass = false;
		}else if(!rePhone.test(phone)){
            $('#phone').parent().children('.error').html('<i class="fa fa-times-circle"></i>手机格式不正确');
            pass = false;
		}
		if(phoneCode === null || phoneCode.trim() === ''){
            $('#phoneCode').parent().children('.error').html('<i class="fa fa-times-circle"></i>请输入手机验证码');
            pass = false;
		}
		if(password === null ||password.trim() === ''){
            $('#form-phone .text-input.pwd').parent().children('.error').html('<i class="fa fa-times-circle"></i>请设置登录密码');
			pass = false;
		}
		if(phone !== passPhone){
		    pass = false;
        }
		if(pass) {
		    $.ajax({
                url: 'phoneandcode',
                method: 'get',
                data: {
                    phone : $('#phone').val(),
                    code : $('#phoneCode').val()
                },
                dataType: 'json',
                success: function(data) {
                    if(data.code === 1001){
                        $('.form-box').hide();
                        $('#phoneOne').hide();
                        var phoneTwoHTML = '<div class="form-group" style="margin-top:100px;">';
                        phoneTwoHTML += '<label for="username" class="text-label">用户名</label>';
                        phoneTwoHTML += '<input type="text" class="form-control-static text-input" name="username" id="username" placeholder="设置用户名" />';
                        phoneTwoHTML += '<span class="error"></span>';
                        phoneTwoHTML += '</div>';
                        phoneTwoHTML += '<div class="form-group">';
                        phoneTwoHTML += '<label for="nickname" class="text-label">昵称</label>';
                        phoneTwoHTML += '<input type="text" class="form-control-static text-input" name="nickname" id="nickname" placeholder="设置昵称" />';
                        phoneTwoHTML += '<span class="error"></span>';
                        phoneTwoHTML += '</div>';
                        phoneTwoHTML += '<div class="radio radio-sex">';
                        phoneTwoHTML += '<span class="text-label">性别</span>';
                        phoneTwoHTML += '<label><input type="radio" name="gender" checked="true" value="0" /><i class="radio-bui"></i>男</label>';
                        phoneTwoHTML += '<label><input type="radio" name="gender" value="1" /><i class="radio-bui"></i>女</label>';
                        phoneTwoHTML += '</div>';
                        phoneTwoHTML += '<div class="form-group">';
                        phoneTwoHTML += '<label for="email" class="text-label">出生日期</label>';
                        phoneTwoHTML += '<input  class="form-control-static text-input" name="birthday" id="birthday"  placeholder="设置出生日期(yyyy-mm-dd)" />';
                        phoneTwoHTML += '<span class="error"></span>';
                        phoneTwoHTML += '</div>';
                        phoneTwoHTML += '<div class="form-group">';
                        phoneTwoHTML += '<label for="job" class="text-label">职务</label>';
                        phoneTwoHTML += '<input type="text" class="form-control-static text-input" name="job" id="job" placeholder="设置职务" />';
                        phoneTwoHTML += '<span class="error"></span>';
                        phoneTwoHTML += '</div>';
                        phoneTwoHTML += '<div class="form-group">';
                        phoneTwoHTML += '<input type="button" class="btn btn-primary  btn-register" value="注册" id="register" />';
                        phoneTwoHTML += '</div>';
                        $('#phoneTwo').html(phoneTwoHTML);
                        $('#birthday').flatpickr();

                        /*为所有input标签添加focus事件*/
                        $('input').on('focus', function() {
                            removeHint(this);
                        })
                        /*为用户名添加校验查询*/
                        checkUsernameIsUsable();
                        /*注册表单校验提交*/
                        $('#register').on('click', function() {
                            var form = $('#form-phone');
                            var pass = validateForm(form);
                            if(pass) {
                                $.ajax({
                                    url: 'create/ph',
                                    method: 'POST',
                                    data: form.serialize(),
                                    dataType: 'json',
                                    success: function(data) {
                                        $('#register').attr('disabled', 'true');
                                        if(data.code === 1001){
                                            layer.msg(data.message, {time:3000});
                                            setTimeout(function() {
                                                location.href = 'http://192.168.43.114:8080/loginnew/index';
                                            }, 3000);
                                        }else if(data.code === 1002){
                                            layer.msg(data.message, {time:2000});
                                            setTimeout(function() {
                                                location.href = 'http://192.168.43.114:8080/registernew/index';
                                            }, 2000);
                                        }else if(data.code === 1003){
                                            var errors = data.data.errors;
                                            var text = '';
                                            for(var i=0;i<errors.length;i++)
                                                text += errors[i] + '\n'
                                            alert(text);
                                            setTimeout(function() {
                                                location.href = 'http://192.168.43.114:8080/registernew/index';
                                            }, 2000);
                                        }else{
                                            layer.msg("注册失败", {time: 2000});setTimeout(function() {
                                                location.href = 'http://192.168.43.114:8080/registernew/index';
                                            }, 2000);
                                        }
                                    },
                                    error: function(err) {
                                        alert('回调接口函数失败');
                                    }

                                })
                            }
                        })
                    } else if(data.code === 1002){
                        $('#phoneCode').parent().children('.error').html('<i class="fa fa-times-circle"></i>' + data.message);
                    } else if(data.code === 1002){
                        $('#phoneCode').parent().children('.error').html('<i class="fa fa-times-circle"></i>' + data.message);
                    } else if(data.code === 1003){
                        $('#phone').parent().children('.error').html('<i class="fa fa-times-circle"></i>' + data.message);
                    }
                },
                error: function(err) {
                    alert("回调函数接口失败");
                }
            })

		}
	})

    /*换一张验证码*/
    $('#codeImg').on('click', function() {
        getCaptcha();
    })

 	/*为所有input标签添加focus事件*/
	$('input').on('focus', function() {
		removeHint(this);
    })

    /*验证邮箱是否已注册*/
    $('#email').on('blur', function() {
        var el = this;
        var email = $(this).val();
        var pass = checkEmail(this, '请输入正确的邮箱地址');
        if(pass) {
            $.ajax({
                url: 'mail',
                method: 'post',
                data: {
                    email : email
                },
                dataType: 'json',
                success: function(data) {
                    console.log(JSON.stringify(data));
                    if(data.code === 1001) {
                        $(el).parent().children('.error ').addClass('success').html('<i class="fa fa-check-circle"></i>' + data.message);
                        passEmail = email;
                    }
                    else
                        $(el).parent().children('.error').removeClass('success').html('<i class="fa fa-times-circle"></i>' + data.message);
                },
                error: function(err) {
                    alert('回调函数接口失败');
                }
            })
        }
    })

    /*验证手机号码是否已注册*/
    $('#phone').on('blur', function() {
        var el = this;
        var phone = $(this).val();
        var pass = checkPhone(this, '请输入正确的手机号码');
        if(pass) {
            $.ajax({
                url: 'phone',
                method: 'post',
                data: {
                    phone : phone
                },
                dataType: 'json',
                success: function(data) {
                    if(data.code === 1001){
                        $(el).parent().children('.error ').addClass('success').html('<i class="fa fa-check-circle"></i>' + data.message);
                        passPhone = phone;
                    }else {
                        $(el).parent().children('.error').removeClass('success').html('<i class="fa fa-times-circle"></i>' + data.message);
                    }
                },
                error: function(err) {
                    alert('回调函数接口失败');
                }
            })
        }

    })
    
})

/**
 * 获取captcha验证码
 */
function getCaptcha(){
	$.ajax({
		url: '/captcha/getCaptchaCode2',
		method: 'GET',
		cache: false,
		success: function(data) {
			$('#codeImg').attr('src', 'data:image/jpeg;base64,' + data);
        },
		error: function(err) {
			alert('回调接口函数失败');
        }
	})
}


/**
 * 表单校验
 * @param {Object} thisForm
 */
function validateForm(thisForm){
	var pass = true;
	with(thisForm){
        pass_1 = checkEmpty(username, '用户名不能为空');
        pass_2 = checkEmpty(nickname, '昵称不能为空');
        pass_3 = checkEmpty(birthday, '出生日期不能为空');
        pass_4 = checkEmpty(job, '职位不能为空');
        pass_5 = checkUsername(username, '用户名命名不规范');
        if(pass_1 && pass_2 && pass_3 && pass_4 && pass_5)
            return true;
        else
            return false;
	}
}

/*验证用户名是否已被使用*/
function checkUsernameIsUsable() {
    $('#username').on('blur', function() {
        var el = this;
        var username = $(this).val();
        var pass = checkEmpty(this, '请输入用户名');
        if(pass) pass = checkUsername(this, '用户名命名不规范');
        if(pass) {
            $.ajax({
                url: 'uname',
                method: 'post',
                data: {
                    username : username
                },
                dataType: 'json',
                success: function(data) {
                    console.log(JSON.stringify(data));
                    if(data.code === 1001) {
                        $(el).parent().children('.error ').addClass('success').html('<i class="fa fa-check-circle"></i>' + data.message);
                        passUsername = username;
                    }
                    else
                        $(el).parent().children('.error').removeClass('success').html('<i class="fa fa-times-circle"></i>' + data.message);
                },
                error: function(err) {
                    alert('回调函数接口失败');
                }
            })
        }
    })
}